package com.playtest;
import java.util.*;
import java.io.*;
import java.net.*;
import android.app.*;
import android.os.*;
import android.view.*;
import android.content.*;
import android.provider.*;
import android.view.View.*;
import android.widget.*;
import android.graphics.drawable.*;
import android.graphics.*;
import android.net.Uri;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.media.MediaPlayer;
import android.util.AttributeSet;
public class MainActivity extends  Activity {


	TextView fb;//=new TextView(this); 
	//public FrameLayout v;
	//RelativeLayout y;
	//LinearLayout k; 
	
	 Context context;
	// VideoView video;
	
    @Override
	int i=0; 
    protected void onCreate(final Bundle savedInstanceState) {

		fb = new TextView(this); 
		super.onCreate(savedInstanceState);
		/*Rect rect = new Rect(); Window win = getWindow(); win.getDecorView().getWindowVisibleDisplayFrame(rect); //状态栏高度
		 statusBarHeight = rect.top; */
		context=this;
		final TextView y1= new TextView(this);
		final EditText y2= new  EditText(this);
		Button y4=new Button(this);
		//final LinearLayout y=new LinearLayout(this);
		final LinearLayout y=new LinearLayout(this);
		y.setOrientation(1);
		y.addView(y1);
		y.addView(y2);
		y.addView(y4);
		y.addView(fb);
		fb.setText("播放视频: " + i);
		y1.setText("请输入播放地址"); 
		y2.setMinHeight(48);
		y2.setHint("请输入播放地址"); 
		y2.setEms(7);
		//y2.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); //限制10个字符
		y4.setText("确认"); 
		y4.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					//	final TextView y3= new TextView(context);
					String text = y2.getText().toString();
					//	y3.setText("您输入的内容是: " +text);
					i++;
					fb.setText("播放视频: " + i);
					playv(text); 
				}});/*
		Thread thread =new Thread(){
            @Override
            public void run() {
				try {
					TextView pp=new TextView(context); 
					y.addView(pp);
					// 创建TCP服务器并绑定到指定端口
					int port = 8888;
					pp.setText("TCP开启 端口: "+port); 
					ServerSocket serverSocket = new ServerSocket(port);
					pp.setText("TCP开启 端口: "+port+"服务器已启动，等待客户端连接...");
					while (true) {
						// 等待客户端连接
						pp.setText("TCP开启 端口: "+port
						+"\n服务器已启动，等待客户端连接..."
						+"\n等待客户端连接"
						);
						
						Socket clientSocket = serverSocket.accept();
						
						pp.setText("客户端连接成功");
						// 创建输入流和输出流
						InputStream inputStream = clientSocket.getInputStream();
						OutputStream outputStream = clientSocket.getOutputStream();

						// 读取客户端发送的数据
						byte[] buffer = new byte[1024];
						int bytesRead = inputStream.read(buffer);
						String receivedMessage = new String(buffer, 0, bytesRead);
						pp.setText("收到消息：" + receivedMessage);
						//playv(receivedMessage);
						if(video!=null)
							video.setVideoPath(receivedMessage);
							video.start(); 
						fb.setText(receivedMessage); 
						// 发送响应数据给客户端
						String responseMessage = "Hello, Client!"+receivedMessage+"\n";
						outputStream.write(responseMessage.getBytes());
						// 关闭连接
						clientSocket.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}; 
		thread.start();*/ 
        setContentView(y);
	}
	void playv(String text) {
		
	    //RelativeLayout v= new RelativeLayout(context); 
		final LinearLayout v=new LinearLayout(context);
		//final VideoView u=new VideoView(context) ;
		final MyVideoView u= new MyVideoView(context); 
		//c.addView(u);
		v.addView(u);
		v.setGravity(Gravity.FILL); 
		/*
		 Drawable background = new Drawable(context); 
		 if (background != null) {
		 u.setBackground(background);
		 }*/
		//y.addView(v);
		u.setLayoutParams(new LinearLayout.LayoutParams(500, 300));  
		/*LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
		 u.setLayoutParams(layoutParams);
		 */
		u.setVideoPath(text);

		if (!Settings.canDrawOverlays(getApplicationContext())) {
			Intent t = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
			startActivityForResult(t, 0);
		}


		//跳转授权

		/*
		 TextView b=new TextView(context); 
		 b.setText("拖动"); 
		 v.addView(b); 
		 */
		//ViewGroup.LayoutParams params  =v.getLayoutParams(); 
		//params.height=300;
		//params.width = 500; 
		//v.setLayoutParams(new LinearLayout.LayoutParams(params)); 
		//设置宽高？


		//final  //或者上去的 等同于 类全局变量public xuanfu f;
		//xuanfu
	    final ppp   f= new ppp(this, v);//new xuanfu(this,v);
		/* pppp   ff=new pppp();
		 final PopupWindow f=ff.pp(this,v);
		 //final PopupWindow f=new PopupWindow(v); 

		 // f.setFocusable(false);
		 f.setOutsideTouchable(false); //点击非PopupWindow视图区域，直接隐藏 (true)开 false关
		 f.setContentView(v);
		 f.setFocusable(false);
		 f.setBackgroundDrawable(new ColorDrawable(0));
		 f.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
		 //f.showAtLocation(f.getContentView(),Gravity.CENTER,0,0);
		 f.showAsDropDown(v, 0, 0);
		 f.setTouchable(true);
		 */
		u.setOnErrorListener(new MediaPlayer.OnErrorListener() {  
				@Override  
				public boolean onError(MediaPlayer mp, int what, int extra) {  
					// 视频播放出错时回调
					if (f != null && f.isShowing()) {
						Toast.makeText(context, "播放出错", Toast.LENGTH_LONG).show();
						if(fb!=null) fb.setText("播放出错视屏地址不对或者没有储存权限");
						i--;
						f.dismiss();
					}
					return false;  
				}  
			});

		u.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {  
				@Override  
				public void onCompletion(MediaPlayer mediaPlayer) {  
					// 视频播放完成时回调  
					/*
					 if (f != null && f.isShowing()) {
					 Toast.makeText(context, "播放结束🔚", Toast.LENGTH_LONG).show();
					 fb.setText("播放结束🔚");
					 f.dismiss();
					 }*/
				}  
			});  

		u.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {  
				@Override  
				public void onPrepared(MediaPlayer mediaPlayer) {  
					// 视频准备完成时回调  
					u.start();
				}  
			});  
		
			
			
		Rect frame = new Rect();    
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);    
		final int statusBarHeight = frame.top;  //状态栏高
		
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		//int screenWidth, screenHeight;
		final int screenWidth = displayMetrics.widthPixels;
		final int screenHeight = displayMetrics.heightPixels;
		int xxo=0; 
		if(screenWidth>screenHeight)
			xxo=(int)(screenHeight*0.03);
		else
			xxo=(int)(screenWidth*0.03);
		final int  xo=xxo; 
		u.setOnTouchListener(new OnTouchListener(){
				@Override
				float p, beix,startx,starty,currx,curry,movex,movey;//X=0,Y=0;
				int biaoti;
			    int X=0,Y=0,XX=-1,YY;
				int dx=0; 
				int xmax,ymax;
				public boolean onTouch(View p1, MotionEvent p2) {
					if (XX == -1) {
						// Toast.makeText(context, "-1配置", Toast.LENGTH_LONG).show();
						XX = u.getWidth();
						YY = u.getHeight(); 
						biaoti = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); 
						Rect outRect = new Rect();
						getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect);
						ymax = outRect.height();
						xmax = outRect.width();

					}

					if (MotionEvent.ACTION_DOWN == p2.getAction()) {
						startx = p2.getRawX();
						starty = p2.getRawY();
						//////TextView a= new TextView(context); 

						//按住屏幕时
						//Toast.makeText(context, "按住 "+starty+"x"+statusBarHeight +" "+Y, Toast.LENGTH_LONG).show();
						if (startx > (X + u.getWidth() - xo) && starty < Y + statusBarHeight+ xo) {
							Toast.makeText(context, "退出+", Toast.LENGTH_LONG).show();
							if (f != null && f.isShowing()) {
								Toast.makeText(context, "退出", Toast.LENGTH_LONG).show();
								if(fb!=null) fb.setText("退出");
								i--;
								f.dismiss();
							}
						}
						dx=0;
						if (startx > (X + u.getWidth() - xo) && starty > (Y + statusBarHeight + u.getHeight()) - xo) {
							//Toast.makeText(context, "调整大小", Toast.LENGTH_LONG).show();
							dx=1;
							}
					} else if (MotionEvent.ACTION_MOVE == p2.getAction()) {
						//在屏幕上滑动时
						currx = p2.getRawX();
						curry = p2.getRawY();
						movex = currx - startx;
						movey = curry - starty;
						if(dx==1){
							XX = XX + (int) movex;
							YY = YY + (int)movey;
							u.setLayoutParams(new LinearLayout.LayoutParams(XX, YY));
							f.update(X, Y, u.getWidth(), u.getHeight());
						} else {
							X = X + (int) movex;
							Y = Y + (int) movey;
							if (X < 0)X = 0;
							if (X > xmax - f.getWidth())X = xmax - f.getWidth();
							if (Y < 0)Y = 0;
							if (Y > ymax - f.getHeight() + biaoti)Y = ymax - f.getHeight() + biaoti;
							f.update(X, Y, u.getWidth(), u.getHeight());
						}
						startx = p2.getRawX();
						starty = p2.getRawY();
						if(fb!=null)fb.setText("当前窗口id\t"+i
									+"\n窗口分辨率\t" + u.getWidth() + "x" + u.getHeight() 
								   + "\n  左上角坐标XxY\t" + X + "x" + (Y + statusBarHeight)
								   + "\n  点击坐标startx*starty\t" + startx + "x" + starty
								   + "\n  当前右下角坐标坐标:\t" + (X + f.getWidth()) + "x" + (Y + f.getHeight() + statusBarHeight)
								   + "\n  可用分辨率\t" + xmax+"x" + ymax
								   + "\n  状态栏高度\t" + statusBarHeight
								   + "\n  屏幕辨率\t" + screenWidth + "x" + screenHeight
								   );

					}

					return false;
				}

			});




		u.setOnClickListener(new OnClickListener(){
				@Override
				float startx,starty;
				public void onClick(View p1) {
					/*if (startx > (X + f.getWidth() - 50) && starty > (Y + statusBarHeight + f.getHeight()) - 50) {
					 }*/

					/*
					 //C = 1;
					 //Toast.makeText(MainActivity.this, "按钮被被播放", Toast.LENGTH_LONG).show();
					 if (start == 0) {
					 u.start();
					 start = 1;
					 } else {
					 start = 0;
					 u.pause();
					 }*/
					u.start();
				}
			});

    }
	
	
	
	
	
	
}



class ppp extends PopupWindow {
	public ppp(Context context, View view) {
		super(context);
		setFocusable(false);
		//setFocusable(true);
		setOutsideTouchable(false); //点击非PopupWindow视图区域，直接隐藏 (true)开 false关
		setContentView(view);
		setBackgroundDrawable(new ColorDrawable(0));
		setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
		showAtLocation(getContentView(), Gravity.NO_GRAVITY/*Gravity.CENTER*/, 0, 0);
	}
}
/*
class pppp {
	PopupWindow pp(Context context, View view) {
	PopupWindow f=new PopupWindow(view); 
		f.setFocusable(false);
		//setFocusable(true);
		f.setOutsideTouchable(false); //点击非PopupWindow视图区域，直接隐藏 (true)开 false关
		f.setContentView(view);
		f.setBackgroundDrawable(new ColorDrawable(0));
		f.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
		f.showAtLocation(f.getContentView(), Gravity.NO_GRAVITY,0,0); //Gravity.CENTER, 0, 0); 
		return f;
	}

	
}*/





 class MyVideoView extends VideoView {
    public MyVideoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyVideoView(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub

        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);
    }
}



